package com.hotelManager.www.servlet;

import com.hotelManager.www.controller.AdminController;
import com.hotelManager.www.po.*;
import com.hotelManager.www.common.Result;
import com.google.gson.Gson;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 管理员端Servlet
 * 处理所有与管理员相关的请求
 */
@WebServlet("/admin/*")
public class AdminServlet extends HttpServlet {
    private final AdminController adminController = new AdminController();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String pathInfo = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取当前登录的管理员用户
            HttpSession session = request.getSession();
            User adminUser = (User) session.getAttribute("user");

            switch (pathInfo) {
                case "/merchants":
                    // 获取所有商家信息
                    List<Shop> merchants = adminController.getAllMerchants().getData();
                    result.put("success", true);
                    result.put("data", merchants);
                    break;

                case "/users":
                    // 获取所有用户信息
                    List<String> roles = List.of("customer", "merchant");
                    List<User> users = adminController.getAllUsersByRoles(roles).getData();
                    result.put("success", true);
                    result.put("data", users);
                    break;

                case "/pending-shops":
                    // 获取待审核的商家
                    List<Shop> pendingShops = adminController.getPendingShops().getData();
                    result.put("success", true);
                    result.put("data", pendingShops);
                    break;

                case "/pending-recharges":
                    // 获取待审核的充值申请
                    List<User> pendingRecharges = adminController.getPendingRechargeUsers().getData();
                    result.put("success", true);
                    result.put("data", pendingRecharges);
                    break;

                case "/signin-statistics":
                    // 获取签到统计信息
                    Map<String, Object> statistics = adminController.getSignInStatistics().getData();
                    result.put("success", true);
                    result.put("data", statistics);
                    break;

                case "/signin/records":
                    // 获取用户签到记录
                    int userId = Integer.parseInt(request.getParameter("userId"));
                    List<SignInRecord> records = adminController.getUserSignInRecords(userId).getData();
                    result.put("success", true);
                    result.put("data", records);
                    break;

                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        response.getWriter().write(gson.toJson(result));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        String pathInfo = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            if (pathInfo == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid API endpoint");
                return;
            }

            switch (pathInfo) {
                case "/shop/approve":
                    // 审核通过店铺
                    handleApproveShop(request, response);
                    return;

                case "/shop/reject":
                    // 审核拒绝店铺
                    handleRejectShop(request, response);
                    return;

                case "/shop/ban":
                    // 封禁店铺
                    handleBanShop(request, response);
                    return;

                case "/shop/unban":
                    // 解封店铺
                    handleUnbanShop(request, response);
                    return;

                case "/user/ban":
                    // 封禁用户
                    handleBanUser(request, response);
                    return;

                case "/user/unban":
                    // 解封用户
                    handleUnbanUser(request, response);
                    return;

                case "/recharge/approve":
                    // 审核通过充值
                    handleApproveRecharge(request, response);
                    return;

                case "/recharge/reject":
                    // 审核拒绝充值
                    handleRejectRecharge(request, response);
                    return;

                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "API endpoint not found");

            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            response.getWriter().write(gson.toJson(result));
        }
    }

    /**
     * 处理审核通过店铺请求
     */
    private void handleApproveShop(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        Result<Void> result = adminController.approveShop(shopId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理审核拒绝店铺请求
     */
    private void handleRejectShop(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        Result<Void> result = adminController.rejectShop(shopId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理封禁店铺请求
     */
    private void handleBanShop(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        Result<Void> result = adminController.banShop(shopId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理解封店铺请求
     */
    private void handleUnbanShop(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer shopId = Integer.parseInt(req.getParameter("shopId"));
        Result<Void> result = adminController.unbanShop(shopId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理封禁用户请求
     */
    private void handleBanUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = Integer.parseInt(req.getParameter("userId"));
        Result<Void> result = adminController.banUser(userId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理解封用户请求
     */
    private void handleUnbanUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = Integer.parseInt(req.getParameter("userId"));
        Result<Void> result = adminController.unbanUser(userId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理审核通过充值请求
     */
    private void handleApproveRecharge(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = Integer.parseInt(req.getParameter("userId"));
        Result<Void> result = adminController.reviewRechargeApplications(userId, true);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理审核拒绝充值请求
     */
    private void handleRejectRecharge(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer userId = Integer.parseInt(req.getParameter("userId"));
        Result<Void> result = adminController.reviewRechargeApplications(userId, false);
        resp.getWriter().write(gson.toJson(result));
    }


}
